package com.rerun.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.servlet.KaptchaExtend;
import com.rerun.common.controller.SuperController;
import com.rerun.entity.SysUser;
import com.rerun.service.ISysLogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录控制器
 *
 * @author Gaojun.Zhou
 * @date 2016年12月14日 下午2:54:01
 */
@Controller
@RequestMapping("/login")
public class LoginController extends SuperController {
	/**
	 * 日志服务
	 */
	@Autowired private ISysLogService sysLogService;

	/**
	 * 登录页面
	 *
	 * @param model the model
	 * @return the string
	 */
	@RequestMapping
	public String login(Model model){
		return "login";
	}

	/**
	 * Get user sys user.
	 *
	 * @param userName the user name
	 * @param password the password
	 * @return the sys user
	 */
	@RequestMapping(value = "/getUser",method=RequestMethod.POST)
     @ResponseBody
	public SysUser getUser(String userName,String password){
		SysUser sysUser=new SysUser();
		sysUser.setPassword(password);
		sysUser.setUserName(userName);
		return sysUser;
	  }

	/**
	 * 执行登录
	 *
	 * @param userName   the user name
	 * @param password   the password
	 * @param captcha    the captcha
	 * @param return_url the return url
	 * @param model      the model
	 * @return the string
	 */
	@RequestMapping(value = "/doLogin",method=RequestMethod.POST)
    public  String doLogin(HttpServletRequest request, String userName, String password, String captcha, String return_url, RedirectAttributesModelMap model){
		
		//验证码校验
		String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if(!code.equals(captcha)) {
			model.addFlashAttribute("error", "验证码不正确");
        	return redirectTo("/login");
		}
		
    	Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		
		 if (!currentUser.isAuthenticated()) {
	          // token.setRememberMe(true);
	            try {
	                currentUser.login(token);
	            } catch (UnknownAccountException uae) {
	            	
	            	model.addFlashAttribute("error", "未知用户");
	            	return redirectTo("/login");
	            } catch (IncorrectCredentialsException ice) {
	            	model.addFlashAttribute("error", "密码错误");
	            	return redirectTo("/login");
	            } catch (LockedAccountException lae) {
	            	model.addFlashAttribute("error", "账号已锁定");
	            	return redirectTo("/login");
	            }
	            catch (AuthenticationException ae) {
	                //unexpected condition?  error?
	            	model.addFlashAttribute("error", "服务器繁忙");
	            	return redirectTo("/login");
	            }
	        }
		/**
		 * 记录登录日志
		 */
		 Subject subject = SecurityUtils.getSubject();
		 SysUser sysUser = (SysUser) subject.getPrincipal();
		 sysLogService.insertLog("用户登录成功",sysUser.getUserName(),request.getRequestURI(),"");
		 return redirectTo("/");
    }

	/**
	 * 验证码
	 *
	 * @throws ServletException the servlet exception
	 * @throws IOException      the io exception
	 */
	@RequestMapping("/captcha")
	@ResponseBody
    public  void captcha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		KaptchaExtend kaptchaExtend =  new KaptchaExtend();
		kaptchaExtend.captcha(request, response);
    }
}
